package com.hotel_management_backstage.lin.service;

import com.hotel_management_backstage.lin.dao.SysMenuMapper;
import com.hotel_management_backstage.lin.entity.SysMenu;
import com.hotel_management_backstage.lin.entity.SysRoleMenu;
import com.hotel_management_backstage.lin.entity.SysUser;
import com.hotel_management_backstage.lin.entity.SysUserRole;
import com.hotel_management_backstage.lin.utils.security.JwtTokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysMenuService {
    @Autowired
    private SysMenuMapper sysMenuMapper;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    public List<SysMenu> getAllByParentId(int parentId){
        return sysMenuMapper.selectAllByParentId(parentId);
    }

    public List<SysMenu> getMenusByCurrentUser(HttpServletRequest request){
        String tokenHeader = request.getHeader(JwtTokenUtils.TOKEN_HEADER);
        // 如果请求头中没有Authorization信息则直接放行了
        if (tokenHeader == null || !tokenHeader.startsWith(JwtTokenUtils.TOKEN_PREFIX)) {
            return null;
        }
        String token = tokenHeader.replace(JwtTokenUtils.TOKEN_PREFIX, "");
        String username = JwtTokenUtils.getUsername(token);
        SysUser sysUser = sysUserService.selectByName(username);

        List<Integer> rids = sysUserRoleService.listByUserId(sysUser.getId()).stream().map(SysUserRole::getRoleId).collect(Collectors.toList());

        List<Integer> menuIds = sysRoleMenuService.selectAllByRid(rids).stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());

        List<SysMenu> menus = sysMenuMapper.selectMenuByManyId(menuIds).stream().distinct().collect(Collectors.toList());

        handleMenus(menus);
        return menus;

    }

        public List<SysMenu> getMenusByRoleId(int rid){
            List<Integer> menuIds = sysRoleMenuService.selectAllByRid(rid).stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());
            System.out.println("menuIds:"+menuIds);
            List<SysMenu> menus = sysMenuMapper.selectMenuByManyId(menuIds);
            System.out.println("menus:"+menus);
            handleMenus(menus);
            return menus;
        }

        public void handleMenus(List<SysMenu> menus){
            menus.forEach(m ->{
                List<SysMenu> children = getAllByParentId(m.getId());
                m.setChildren(children);
            });

            menus.removeIf(m -> m.getParentId() != 0);
        }
}
